from django.http import JsonResponse
from django.shortcuts import render

from blueking.component.shortcuts import get_client_by_request
from .contants import *
import json
import time
from .models import BackupRecord
def home(request):
    """
    首页
    """
    return render(request, "bk_framework_app/index_home.html")


def dev_guide(request):
    """
    开发指引
    """
    return render(request, "bk_framework_app/dev_guide.html")


def contact(request):
    """
    联系页
    """
    return render(request, "bk_framework_app/contact.html")



def get_bizs_list(request):
    """
    获取业务列表
    """
    # 从环境配置获取 APP 信息，从 request 获取当前用户信息
    client = get_client_by_request(request)
    # 请求参数
    kwargs = {
        "fields": [
            "bk_biz_id",
            "bk_biz_name"
        ],
        # 社区版环境中业务数量有限，故不考虑分页情况
        "page": {
            "start": 0,
            "limit": 10,
            "sort": ""
        }
    }
    # 这里需要填写对应的组件 API 的入口地址
    result = client.cc.search_business(kwargs)
    return JsonResponse(result)

def get_sets_list(request):
    client = get_client_by_request(request)
    kwargs = {
        "bk_biz_id": request.GET.get('bk_biz_id'),
        "fields": ["bk_set_id", "bk_set_name", "bk_biz_id", "bk_created_at", "bk_supplier_account"]
    }
    response = client.cc.search_set(kwargs)
    return JsonResponse(response)


def get_modules_list(request):
    client = get_client_by_request(request)
    kwargs = {
        "bk_biz_id": request.GET.get('bk_biz_id'),
        "bk_set_id": request.GET.get("bk_set_id"),
        "fields": ["bk_module_id", "bk_module_name", "bk_set_id", "bk_biz_id", "bk_created_at", "bk_supplier_account"]
    }
    response = client.cc.search_module(kwargs)
    return JsonResponse(response)


def get_hosts_list(request):
    client = get_client_by_request(request)
    kwargs = {
        "bk_biz_id": request.GET.get('bk_biz_id'),
        "page": {"start": 0, "limit": 100, },
        "fields": ["bk_host_id", "bk_cloud_id", "bk_host_innerip", "bk_os_type", "bk_mac", "operator",
                   "bk_bak_operator"]
    }
    if request.GET.get("bk_set_id"):
        kwargs["bk_set_ids"] = [int(request.GET.get("bk_set_id"))]
    if request.GET.get("bk_module_id"):
        kwargs["bk_module_ids"] = [int(request.GET.get("bk_module_id"))]
    rules = []
    if request.GET.get("operator"):
        rules.append({
            "field": "operator",
            "operator": "equal",
            "value": request.GET.get("operator")

        })
    if rules:
        kwargs["host_property_filter"] = {
            "condition": "AND",
            "rules": rules
        }
    response = client.cc.list_biz_hosts(kwargs)
    return JsonResponse(response)


def get_host_detail(request):
    client = get_client_by_request(request)
    kwargs = {
        "bk_host_id": request.GET.get('bk_host_id')
    }
    response = client.cc.get_host_base_info(kwargs)
    return JsonResponse(response)

def search_file(request):
    """
    根据主机IP、文件目录和文件后缀，查询符合条件的主机文件
    """
    # 注意：先在 constants.py 中替换 SEARCH_FILE_PLAN_ID 为你自己在作业平台上新建的方案的 ID
    host_id_list_str = request.GET.get("host_id_list")
    host_id_list = [int(bk_host_id) for bk_host_id in host_id_list_str.split(",")]
    kwargs = {
        "bk_scope_type": "biz",
        "bk_scope_id": JOB_BK_BIZ_ID,
        "job_plan_id": SEARCH_FILE_PLAN_ID,

        "global_var_list": [
            {
                "name": "host_list",
                "server": {
                    "host_id_list": host_id_list,
                },
            },
            {
                "name": "search_path",
                "value": request.GET.get("search_path"),
            },
            {
                "name": "suffix",
                "value": request.GET.get("suffix"),
            },
        ],
    }
    # 调用执行方案
    client = get_client_by_request(request)
    job_instance_id = client.jobv3.execute_job_plan(**kwargs).get("data").get("job_instance_id")
    kwargs = {
        "bk_scope_type": "biz",
        "bk_scope_id": JOB_BK_BIZ_ID,
        "job_instance_id": job_instance_id,
    }
    attempts = 0
    while attempts < MAX_ATTEMPTS:
        # 获取执行方案执行状态
        step_instance_list = client.jobv3.get_job_instance_status(**kwargs).get("data").get("step_instance_list")
        if step_instance_list[0].get("status") == WAITING_CODE:
            time.sleep(JOB_RESULT_ATTEMPTS_INTERVAL)
        elif step_instance_list[0].get("status") != SUCCESS_CODE:
            res_data = {
                "result": False,
                "code": WEB_SUCCESS_CODE,
                "message": "search failed",
            }
            return JsonResponse(res_data)
        elif step_instance_list[0].get("status") == SUCCESS_CODE:
            break
        attempts += 1

    step_instance_id = step_instance_list[0].get("step_instance_id")

    log_list = []
    for bk_host_id in host_id_list:
        data = {
            "bk_scope_type": "biz",
            "bk_scope_id": JOB_BK_BIZ_ID,
            "job_instance_id": job_instance_id,
            "step_instance_id": step_instance_id,
            "bk_host_id": bk_host_id,
        }
        # 查询执行日志
        response = client.jobv3.get_job_instance_ip_log(**data).get("data")
        step_res = response.get("log_content")
        json_step_res = json.loads(step_res)
        json_step_res["bk_host_id"] = response.get("bk_host_id")
        log_list.append(json_step_res)
    res_data = {
        "result": True,
        "code": WEB_SUCCESS_CODE,
        "data": log_list,
    }
    return JsonResponse(res_data)


def backup_file(request):
    """
    根据主机IP、文件目录和文件后缀，备份符合条件的主机文件到指定目录
    """
    # 注意：先在 constants.py 中替换 BACKUP_FILE_PLAN_ID 为你自己在作业平台上新建的方案的 ID
    host_id_list_str = request.GET.get("host_id_list")
    host_id_list = [int(bk_host_id) for bk_host_id in host_id_list_str.split(",")]
    search_path = request.GET.get("search_path")
    suffix = request.GET.get("suffix")
    kwargs = {
        "bk_scope_type": "biz",
        "bk_scope_id": JOB_BK_BIZ_ID,
        "job_plan_id": BACKUP_FILE_PLAN_ID,

        "global_var_list": [
            {
                "name": "host_list",
                "server": {
                    "host_id_list": host_id_list,
                },
            },
            {
                "name": "search_path",
                "value": search_path
            },
            {
                "name": "suffix",
                "value": suffix
            },
            {
                "name": "backup_path",
                "value": request.GET.get("backup_path"),
            },
        ],
    }
    # 调用执行方案
    client = get_client_by_request(request)
    job_instance_id = client.jobv3.execute_job_plan(**kwargs).get("data").get("job_instance_id")
    kwargs = {
        "bk_scope_type": "biz",
        "bk_scope_id": JOB_BK_BIZ_ID,
        "job_instance_id": job_instance_id,
    }
    attempts = 0
    while attempts < MAX_ATTEMPTS:
        # 获取执行方案执行状态
        step_instance_list = client.jobv3.get_job_instance_status(**kwargs).get("data").get("step_instance_list")
        if step_instance_list[0].get("status") == WAITING_CODE:
            time.sleep(JOB_RESULT_ATTEMPTS_INTERVAL)
        elif step_instance_list[0].get("status") != SUCCESS_CODE:
            res_data = {
                "result": False,
                "code": WEB_SUCCESS_CODE,
                "message": "backup failed",
            }
            return JsonResponse(res_data)
        elif step_instance_list[0].get("status") == SUCCESS_CODE:
            break
        attempts += 1
    step_instance_id = step_instance_list[0].get("step_instance_id")
    for bk_host_id in host_id_list:
        data = {
            "bk_scope_type": "biz",
            "bk_scope_id": JOB_BK_BIZ_ID,
            "job_instance_id": job_instance_id,
            "step_instance_id": step_instance_id,
            "bk_host_id": bk_host_id,
        }
        # 查询执行日志
        response = client.jobv3.get_job_instance_ip_log(**data).get("data")
        step_res = response.get("log_content")
        json_step_res = json.loads(step_res)
        for step_res in json_step_res:
            # 创建备份记录
            step_res["bk_host_id"] = bk_host_id
            step_res["bk_file_dir"] = search_path
            step_res["bk_file_suffix"] = suffix
            step_res["bk_file_operator"] = request.user.username
            step_res["bk_job_link"] = "{}/biz/{}/execute/task/{}".format(
                BK_JOB_HOST,
                JOB_BK_BIZ_ID,
                job_instance_id,
            )
            BackupRecord.objects.create(**step_res)
    res_data = {
        "result": True,
        "data": "success",
        "code": WEB_SUCCESS_CODE,
    }
    return JsonResponse(res_data)


def get_backup_record(request):
    """
    查询备份记录
    """
    res_data = {
        "result": True,
        "data": list(BackupRecord.objects.all().order_by("-id").values()),
        "code": WEB_SUCCESS_CODE,
    }
    return JsonResponse(res_data)
